package com.sscaipiao.android.activity.service;

import java.io.IOException;
import java.util.Date;
import java.util.List;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Vibrator;
import android.text.format.Time;
import android.util.Log;

import com.sscaipiao.android.activity.HallActivity;
import com.sscaipiao.android.common.Constants;
import com.sscaipiao.android.model.User;
import com.sscaipiao.android.utils.CaipiaoServiceHelper;
import com.sscaipiao.android.utils.DateUtil;
import com.sscaipiao.android.utils.UserDataServiceHelper;

public class NotificationService extends Service {

	private boolean threadDisable;
    //定义个一个Tag标签  
    private static final String TAG = "SSCaipiaoService";  
    //这里定义吧一个Binder类，用在onBind()有方法里，这样Activity那边可以获取到  
    private MyBinder mBinder = new MyBinder(); 
    
	// 声明通知（消息）管理器 只要知道它是用来管理通知消息就行  
    NotificationManager m_NotificationManager;
    PendingIntent m_PendingIntent;  
    // 声明Notification对象  
    Notification m_Notification;  
    Intent m_Intent; 
       
    User user = null;
    
    private int notification_id = 2012;
    
    @Override  
    public IBinder onBind(Intent intent) {  
        Log.v(TAG, "start IBinder~~~");  
        return mBinder;  
    }  
    @Override  
    public void onCreate() {  
        Log.v(TAG, "start onCreate~~~");  
        
     // 初始化NotificationManager对象 Get a reference to the NotificationManager  
        m_NotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);  
        
        // 点击通知时转移内容也就是从哪个Activity跳到哪个Activity 这里是从Activity01跳到Activity02  
        m_Intent = new Intent(NotificationService.this, HallActivity.class); 
		Bundle b = new Bundle();
		if (user == null) {
			user = new User();
		}

		//user.setToken(retUser.getToken());
		b.putSerializable(Constants.USER, user);
		m_Intent.putExtras(b);
        
        // Pending这个词是“挂起”、“暂挂”的意思 我就理解为一个挂起 或者暂挂的 Intent 临时的留着一会用 xh  
        // E文实在是差看不懂文档  
        m_PendingIntent = PendingIntent.getActivity(NotificationService.this, 0,  
                m_Intent, 0);  
        // 构造Notification对象 它就是一个通知消息对象 我们只要知道我们要在手机最上边状态栏通知消息的时候就用这个对象  
        m_Notification = new Notification(); 
        
        super.onCreate();  
    }  
      
    @Override  
    public void onStart(Intent intent, int startId) {  
        Log.v(TAG, "start onStart~~~");  
        super.onStart(intent, startId);
        
		Bundle bundle = null;
		if(intent != null){
			bundle = intent.getExtras();
		}

		if(bundle != null){
				if (bundle.containsKey(Constants.USER)) {
					user = (User) bundle.get(Constants.USER);
				}

			Log.v("MyService on Start ", user.getAccount());
		}
		
        new Thread( new Runnable() {
            @Override
            public void run() {
                while ( ! threadDisable) {               	
                	try {
                		
    					user = UserDataServiceHelper.login(NotificationService.this,
    							user.getAccount(), user.getPassword());
    					
    					List<String> bets = CaipiaoServiceHelper.getBetList(NotificationService.this, user,
    							null, 
    							DateUtil.getDate(null, new Date((new Date()).getTime()- 1000*60*60*24*2)) , 
    							DateUtil.getDate(null, new Date()), 
    							null, null, Constants.BET_STATUS_BINGO);
    	
						
						boolean haveNewAlert = bets.size() >0;
						//haveNewAlert = true;
						if(haveNewAlert) {
							
							for(String bet : bets) {
								notification(bet.split(Constants.STRING_SPLITE_COMPLEX)[2], 
										bet.split(Constants.STRING_SPLITE_COMPLEX)[3],
										bet.split(Constants.STRING_SPLITE_COMPLEX)[7]); 
							}
							 
							 //Log.v("(prop.getOpenVibra", prop.getOpenVibra());
//							 if(Constants.trueStr.equals(prop.getOpenVibra())){
//								 long[] vibrate = {0,400,800,500}; //0毫秒后开始振动，振动400毫秒后停止，再过800毫秒后再次振动500毫秒 
//									m_Notification.vibrate = vibrate;
//								 //vibrate(); 
//							 } else {
//								 m_Notification.vibrate = null;
//							 }
//							 //Log.v("prop.getSilent()", prop.getSilent());
//							 if(Constants.trueStr.equals(prop.getSilent())){
//								 m_Notification.sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); 
//								 //sound();
//							 }else{
//								 m_Notification.sound = null;
//							 }		                    							 
						}						
                	} catch (IOException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
  
                    try {
                        Thread.sleep( 24 *60*60*1000 );
					
                    } catch (InterruptedException e) {
                    }
                }
            }

			
        }).start();
    }  
    
    private void notification( String betName, String betPeriod , String awardMoney) {
		// 设置通知在状态栏显示的图标  
		//m_Notification.icon = R.drawable.ic_launcher_ss;  
		// 当我们发送通知时在状态栏显示的内容 这个显示时暂时的大家试试就知道了  
		m_Notification.tickerText = "中奖通知";  
		// 通知时发出默认的声音 这个defaults是Notification的一个int型的变量  
		// DEFAULT_SOUND是Notification这个类已经定义好的常量直接用就O 了  
		//m_Notification.defaults = Notification.DEFAULT_SOUND;  
		// 设置通知显示的参数 (Context context, CharSequence contentTitle,  
		// CharSequence contentText, PendingIntent contentIntent)  
		// 参数1上下文对象Context 参数2 类似标题Title 这里大家试试 看看那些文字显示在那个位置明白意思就OK  
		m_Notification.setLatestEventInfo(NotificationService.this, betName+" "+ betPeriod + " 中奖  " + awardMoney,  
		        "点击查看详情", m_PendingIntent);  
		// 可以理解为执行这个通知 或者说 由NotificationManager对象或者它的一个引用把  
		// 通知发出去然后就会在状态栏显示了  
		// 详细信息大家可以查看文档  
		//m_Notification.number  =1;
		//使用Notification的number属性，默认为0，如果是1或更大的数字，则会在图标上覆盖显示这个数字。
		m_NotificationManager.cancel(notification_id);
		m_NotificationManager.notify(notification_id, m_Notification);

	}

	private void sound() {
		MediaPlayer mp = new MediaPlayer();
		mp.reset();                    
		try {
			mp.setDataSource(mBinder.getService(),RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		try {
			mp.prepare();
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		mp.start();
		try {
		    Thread.sleep( 3*1000 );
		} catch (InterruptedException e) {
		}
		mp.stop();
	}

	private void vibrate() {
		Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE); 
		vibrator.vibrate(1000);
	}
      
    @Override  
    public void onDestroy() {  
        Log.v(TAG, "start onDestroy~~~");  
        super.onDestroy();  
        this .threadDisable = true ;

    }  
      
      
    @Override  
    public boolean onUnbind(Intent intent) {  
        Log.v(TAG, "start onUnbind~~~");  
        return super.onUnbind(intent);  
    }  
      
    //这里我写了一个获取当前时间的函数，不过没有格式化就先这么着吧  
    public String getSystemTime(){  
          
        Time t = new Time();  
        t.setToNow();  
        return t.toString();  
    }  
      
    public class MyBinder extends Binder{  
        public NotificationService getService()  
        {  
            return NotificationService.this;  
        }  
    }  

}
